﻿using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{
    public Vector3 offset;
    public Transform playerTransform;

    [Header("Shaking Effect")]
    // How long the camera shaking.
    public float shakeDuration = 0.1f;
    // Amplitude of the shake. A larger value shakes the camera harder.
    public float shakeAmount = 0.2f;
    public float decreaseFactor = 0.3f;
    [HideInInspector]
    public Vector3 originalPos;

    private Vector3 originalDistance;
    private float currentShakeDuration;
    private float currentDistance;

    private void Start()
    {
        playerTransform = FindObjectOfType<PlayerController>().transform;
    }

    void Update()
    {
        if (GameManager.Instance)
        {
            if (GameManager.Instance.GameState == GameState.Playing)
            if (playerTransform)
            {
                Vector3 target = new Vector3(playerTransform.position.x, this.transform.position.y, this.transform.position.z) + offset; // Camera follows the player with specified offset position
                transform.position = Vector3.MoveTowards(transform.position, target, 0.5f);
            }
        }  
    }

    public void ShakeCamera()
    { 
        StartCoroutine(Shake());
    }

    IEnumerator Shake()
    {
        originalPos = transform.position;
        currentShakeDuration = shakeDuration;
        while (currentShakeDuration > 0)
        {
            Vector2 pos = originalPos + Random.insideUnitSphere * shakeAmount;
            transform.position = pos;
            currentShakeDuration -= Time.deltaTime * decreaseFactor;
            yield return null;
        }
    }
}
